//
//  GKZYViewController.m
//  GKZY_CLASS
//
//  Created by KwokChun Cheung on 15/11/25.
//  Copyright © 2015年 eenet. All rights reserved.
//

#import <JGProgressHUD/JGProgressHUD.h>
#import <Masonry/Masonry.h>
#import <SBJson/SBJson.h>

#import "GKZYHomeViewController.h"
#import "GKZYLoginViewController.h"
#import "GKZYHomeTermCell.h"
#import "GKZYHomeInfoAreaView.h"

#import "GKZYStudySituationReq.h"
#import "GKZYCourseListReq.h"
#import "GKZYCourseStudyInfoEntity.h"
#import "GKZYCourseEntity.h"
#import "GKZYLoginUserInfoEntity.h"

#import "ApiGuoKaiHepler.h"
#import "ResourceHelper.h"
#import "ClassHelper.h"
#import "xxptmobile-Defines.h"

#import "GKZYCustomPushAnimation.h"
#import "GKZYCustomDismissedAnimation.h"
#import "GKZYExamineWebViewController.h"

#pragma mark - OOHomeModel

@implementation GKZYHomeModel
@end

#pragma mark - OOHomeViewController

@interface GKZYHomeViewController ()<GKZYHomeCourseCellDelegate>
@property (nonatomic, strong) UIView *navigationArea;
@property (nonatomic, strong) UIView *navigationTitleArea;
@property (nonatomic, strong) UILabel *navigationTitleLabel;

@property (nonatomic, strong) GKZYHomeTermAreaView *termArea;
@property (nonatomic, strong) GKZYHomeCourseAreaView *courseArea;

@property (nonatomic, strong) GKZYCustomPushAnimation *pushAnimation;
@property (nonatomic, strong) GKZYCustomDismissedAnimation *dismissedAnimation;
@end

@implementation GKZYHomeViewController{
    ApiGuoKaiHepler *apiHepler;
    JGProgressHUD *progress;
}

-(UIStatusBarStyle)preferredStatusBarStyle{
    //不使用系统导航栏下修改状态栏颜色
    return UIStatusBarStyleLightContent;
}

-(void)initProperty{
    apiHepler = [ApiGuoKaiHepler new];
    progress = [[JGProgressHUD alloc]initWithStyle:JGProgressHUDStyleDark];
    
    self.pushAnimation = [GKZYCustomPushAnimation new];
    self.dismissedAnimation = [GKZYCustomDismissedAnimation new];
    self.model = [GKZYHomeModel new];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(alterError:) name:HOME_ALTER_ACTIVED_ERROR object:nil];
}

-(instancetype)init{
    if (self = [super init]) {
        [self initProperty];
    }
    return self;
}

-(instancetype)initWithSid:(NSString *)sid{
    if (self = [self init]) {
        self.sid = sid;
    }
    return self;
}

-(void)viewDidLoad {
    [super viewDidLoad];
    
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.view.backgroundColor = [UIColor lightGrayColor];
    
    [self.view addSubview:self.navigationArea];
    [self.navigationArea mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.height.equalTo(@(64));
    }];
    
    [self.navigationArea addSubview:self.navigationTitleArea];
    [self.navigationTitleArea mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.navigationArea);
        make.centerY.equalTo(self.navigationArea).multipliedBy(1.3);
    }];
    
    [self.view addSubview:self.termArea];
    [self.termArea mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.navigationArea.mas_bottom);
        make.left.right.equalTo(self.view);
    }];
    
    [self.view insertSubview:self.courseArea belowSubview:self.termArea];
    [self.courseArea mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.navigationArea.mas_bottom);
        make.left.right.bottom.equalTo(self.view);
    }];
    self.courseArea.superController = self;
    
    if (self.sid) {
        [progress showInView:self.view animated:YES];
        [self requestCatBy:self.sid];
    }
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

#pragma mark - OOHomeCourseCellDelegate
- (void)OOHomeCourseCellDelegateShouldPresentNextViewControllerWithSender:(UIView *)sender{
    GKZYHomeCourseModel *courseModel = [GKZYHomeCourseModel new];
    if ([sender.superview isKindOfClass:[GKZYHomeCourseCell class]]) {
        GKZYHomeCourseCell *cell = (GKZYHomeCourseCell *)sender.superview;
        courseModel = cell.model;
    }
    
    if ((courseModel.courseStatus == GKZYHomeCourseRetry
        || courseModel.courseStatus == GKZYHomeCoursePass)
        && ![courseModel.examUrl isEqualToString:@""]
        && [courseModel.examUrlAble intValue] == 1) {//1:有效 2:无效
        
        //@"http://exam.tt.chinaeenet.com/exam/examapp/loginApp.do?formMap.CHOOSE_ID=e40c05ae5d5c4ee48dcaa98fd05ad6b5&formMap.FORAPP=IOS";
        NSString *iosPath = [courseModel.examUrl stringByAppendingString:@"&formMap.FORAPP=IOS"];
        GKZYExamineWebViewController *vc = [[GKZYExamineWebViewController alloc] initWithURLPath:iosPath];
        vc.transitioningDelegate = self;
        [self presentViewController:vc animated:YES completion:nil];
    }
}


#pragma mark - Test Methods

-(GKZYHomeModel *)adjustHomeModel{
    GKZYHomeModel *model = [GKZYHomeModel new];
    model.title = @"第一学期";
    model.terms = [self adjustTermData];
    model.courses = [self adjustCourseData];
    model.infoArray = [self adjustInfoData];
    return model;
}

-(NSMutableArray *)adjustTermData{
    NSMutableArray *datas = [[NSMutableArray alloc]init];
    for (int i=0; i<5; i++) {
        GKZYHomeTermModel *model = [GKZYHomeTermModel new];
        model.identity = [NSString stringWithFormat:@"%d",i+1];
        model.title = [NSString stringWithFormat:@"2014 春第%d学习",i];
        model.dateRange = [NSString stringWithFormat:@"2014-02-24 至 2014-07-20"];
        model.checked = i==0;
        [datas addObject:model];
    }
    return datas;
}

-(NSMutableArray *)adjustCourseData{
    NSMutableArray *datas = [[NSMutableArray alloc]init];
    for (int i=0; i<30; i++) {
        GKZYHomeCourseModel *model = [GKZYHomeCourseModel new];
        model.title = [NSString stringWithFormat:@"管理方式与艺术 %d",i];
        
        model.scoreForRequired = [NSString stringWithFormat:@"%d",i];
        model.rateForLearning = [NSString stringWithFormat:@"%d",i*7];
        model.rateForStudyMark = @"40";
        model.scoreForStudyMark = [NSString stringWithFormat:@"%d",i+90];
        model.rateForExamMark = @"60";
        model.scoreForExamMark = @"0";
        model.rateForTotalMark = @"90";
        model.scoreForTotalMark = @"0";
        switch (i) {
            case 8:
                model.courseStatus = GKZYHomeCoursePass;
                model.rateForLearning = @"90";
                model.isRequired = NO;
                break;
            case 9:
                model.courseStatus = GKZYHomeCourseRetry;
                model.rateForLearning = @"80";
                model.isRequired = NO;
                break;
            case 10:
                model.courseStatus = GKZYHomeCourseFinish;
                model.rateForLearning = @"100";
                model.isRequired = NO;
                break;
            default:
                model.courseStatus = GKZYHomeCourseNone;
                model.isRequired = YES;
                break;
        }
        [datas addObject:model];
    }
    return datas;
}

-(NSMutableArray *)adjustInfoData{
    NSMutableArray *infoArray = [NSMutableArray array];
    for (int i = 0; i < 5; i++) {
        GKZYHomeInfoModel *model = [GKZYHomeInfoModel new];
        model.detail = @"期末成绩";
        model.info = @"67";
        [infoArray addObject:model];
    }
    return infoArray;
}

#pragma mark - Request Methods

-(void)requestCatBy:(NSString *)sid{
    
    __weak typeof(self) weakSelf = self;
    
//    /**********************测试数据**************************/
//    [apiHepler setIsTest:YES];
//    /**********************测试数据**************************/
    
    NSDictionary *dic = @{@"sid":sid};
    [apiHepler toPOST:API_KEY_GKZY_COURSE_CAT andParameters:dic andContentType:GKZYJsonContentType andSync:YES andSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSString *errorMsg = responseObject[@"message"];
            if (errorMsg) {
                [progress dismissAfterDelay:0.2f];
                
                NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
                BOOL logFlag = [[userDefaults valueForKey:OO_USER_ALREADLY_LOGIN] boolValue];
                
                if (logFlag) {
                    GKZYLoginViewController *vc = [[GKZYLoginViewController alloc] initOnLogout];
                    [weakSelf presentViewController:vc animated:YES completion:nil];
                }else{
                    [weakSelf.navigationController popViewControllerAnimated:YES];
                }
                
                [[NSNotificationCenter defaultCenter] postNotificationName:OO_LOGIN_USER_ERROR object:errorMsg];
                
                return;
            }
        }
        
        if ([responseObject isKindOfClass:[NSArray class]]) {
            NSArray *responseArray = (NSArray *)responseObject;
            if ([responseArray isEqualToArray:@[]]) {
                [progress dismissAfterDelay:0.2f];
                [self alterErrorWithMsg:@"暂无课程，请联系班主任"];
                return;
            }
        }
        
        NSMutableArray<GKZYHomeTermModel *> *terms = [[NSMutableArray alloc]init];
        for (NSDictionary *term in responseObject) {
            GKZYHomeTermModel *termModel = [GKZYHomeTermModel new];
            termModel.identity = term[@"id"];
            termModel.title = term[@"name"];
            [terms addObject:termModel];
        }
        
        if (terms.count<=0) { return; }
        
        GKZYHomeModel *homeModel = weakSelf.model;
        homeModel.terms = terms;
        homeModel.title = terms[weakSelf.currentIndex].title;
        [weakSelf setModel:homeModel];
        
        weakSelf.currentPage = weakSelf.currentPage == nil ? @1 : weakSelf.currentPage ;
        weakSelf.currentCid = weakSelf.currentCid == nil ? terms[0].identity : weakSelf.currentCid;
        
        //studyInfo
        GKZYStudySituationReq *studyInfoReq = [GKZYStudySituationReq new];
        studyInfoReq.sid = sid;
        studyInfoReq.cid = weakSelf.currentCid;
        [weakSelf requestStudyInfo:studyInfoReq];
        
        //courseList
        GKZYCourseListReq *courseReq = [GKZYCourseListReq new];
        courseReq.sid = sid;
        courseReq.cid = weakSelf.currentCid;
        courseReq.pageNo = [weakSelf.currentPage stringValue];
        courseReq.pageSize = OO_PAGE_NO;
        [weakSelf requestList:courseReq isAdd:NO onLoading:NO];
        
    } andFailure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        
    }];
}

-(void)requestStudyInfo:(GKZYStudySituationReq *)req{
    [apiHepler toPOST:API_KEY_GKZY_STUDY_SITUATION andReq:req andContentType:GKZYJsonContentType andSync:YES andSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        if ([responseObject isKindOfClass:[NSArray class]]) {
            NSMutableArray *infoArray = [NSMutableArray array];
            for (NSDictionary *infoDic in responseObject) {
                GKZYHomeInfoModel *infoModel = [GKZYHomeInfoModel new];
                infoModel.detail = [NSString stringWithFormat:@"%@", infoDic[@"name"]];
                infoModel.info = [NSString stringWithFormat:@"%@", infoDic[@"value"]];
                [infoArray addObject:infoModel];
            }
            self.model.infoArray = infoArray;
        }
        
    } andFailure:nil];
}

-(void)requestList:(GKZYCourseListReq *)req isAdd:(BOOL)isAdd onLoading:(BOOL)onLoading{
    
    __weak typeof(self) weakSelf = self;
    
    if (onLoading) {
        [progress showInView:self.view animated:YES];
    }
    
    [apiHepler toPOST:API_KEY_GKZY_COURSE_LIST andReq:req andContentType:GKZYJsonContentType andSync:YES andSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSMutableArray *courses = [[NSMutableArray alloc]init];
        if (isAdd) {
            courses = self.courseArea.courses;
        }
        for (NSDictionary *course in responseObject[@"dataList"]) {
            GKZYCourseEntity *courseEntity = [GKZYCourseEntity new];
            [ClassHelper copyDicFrom:course to:courseEntity];
            
            GKZYHomeCourseModel *courseModel = [GKZYHomeCourseModel new];
            courseModel.identity = courseEntity.id;
            courseModel.classId = courseEntity.classId;
            courseModel.courseId = courseEntity.courseId;
            courseModel.title = courseEntity.name;
            courseModel.isRequired = [courseEntity.courseStyle intValue]==1;
            courseModel.scoreForRequired = [courseEntity.credit stringValue];
            courseModel.scoreForExamMark = [courseEntity.examScore stringValue];
            courseModel.scoreForStudyMark = [courseEntity.studyScore stringValue];
            courseModel.scoreForTotalMark = [courseEntity.totalScore stringValue];
            courseModel.rateForExamMark = [courseEntity.examScorePercent stringValue];
            courseModel.rateForStudyMark = [courseEntity.studyScorePercent stringValue];
            courseModel.rateForTotalMark = [courseEntity.passScore stringValue];
            courseModel.rateForLearning = [courseEntity.progress stringValue];
            courseModel.examUrl = courseEntity.examUrl;
            courseModel.examId = courseEntity.examId;
            courseModel.examState = courseEntity.examState;
            courseModel.examUrlAble = courseEntity.examUrlAble;
            courseModel.examTip = courseEntity.examTip;
            
            if ([courseEntity.examState intValue] == 1) {//无考试活动
                courseModel.courseStatus = GKZYHomeCourseNone;
            }else if([courseEntity.examState intValue] == 2){//有考试活动
                courseModel.courseStatus = GKZYHomeCoursePass;
            }else if([courseEntity.examState intValue] == 3){//通过考试或等待考试结果
                courseModel.courseStatus = GKZYHomeCourseFinish;
            }else if([courseEntity.examState intValue] == 4){//考试未通过
                courseModel.courseStatus = GKZYHomeCourseRetry;
            }else{
                courseModel.courseStatus = GKZYHomeCourseNone;
            }
            
            [courses addObject:courseModel];
        }
        
        GKZYHomeModel *homeModel = weakSelf.model;
        homeModel.courses = courses;
        [weakSelf setModel:homeModel];
        
        [progress dismissAfterDelay:0.2f];
        
    } andFailure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [progress dismissAfterDelay:0.2f];
    }];
}

#pragma mark - Setter For Property

-(void)setModel:(GKZYHomeModel *)model{
    _model = model;
    
    if (model) {
        self.navigationTitleLabel.text = model.title;
        self.termArea.terms = model.terms;
        self.courseArea.courses = model.courses;
        self.courseArea.infoArray = model.infoArray;
    }
}

#pragma mark - Getter For UI

-(UIView *)navigationArea{
    if (!_navigationArea) {
        _navigationArea = ({
            UIView *view = [UIView new];
            view.backgroundColor = [UIColor colorWithRed:67/255.0 green:128/255.0 blue:203/255.0 alpha:1];
            view;
        });
    }
    return _navigationArea;
}

-(UIView *)navigationTitleArea{
    if (!_navigationTitleArea) {
        _navigationTitleArea = ({
            UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 100, 30)];
            
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(toggleTermArea)];
            [view addGestureRecognizer:tap];
            view.userInteractionEnabled = YES;
            
            [view addSubview:self.navigationTitleLabel];
            [self.navigationTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.bottom.left.equalTo(view);
            }];
            
            UILabel *icon = [UILabel new];
            icon.font = [[ResourceHelper archiveFont:FONT_FONTAWESOME withType:@"otf"] fontWithSize:14];
            icon.text = @"\U0000F078";
            icon.textColor = [UIColor whiteColor];
            [icon sizeToFit];
            [view addSubview:icon];
            [icon mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(self.navigationTitleLabel.mas_right).offset(5);
                make.centerY.equalTo(view);
                make.right.equalTo(view);
            }];
            view;
        });
    }
    return _navigationTitleArea;
}

-(UILabel *)navigationTitleLabel{
    if (!_navigationTitleLabel) {
        _navigationTitleLabel = ({
            UILabel *label = [UILabel new];
            label.textColor = [UIColor whiteColor];
            label.font = [UIFont systemFontOfSize:18];
            label;
        });
    }
    return _navigationTitleLabel;
}

-(GKZYHomeTermAreaView *)termArea{
    if (!_termArea) {
        _termArea = ({
            GKZYHomeTermAreaView *view = [GKZYHomeTermAreaView new];
            view.superController = self;
            view.cellClick = ^(NSString *identity, NSString *title){
                self.model.title = title;
                GKZYCourseListReq *courseReq = [GKZYCourseListReq new];
                courseReq.sid = self.sid;
                courseReq.cid = identity;
                courseReq.pageNo = [self.currentPage stringValue];
                courseReq.pageSize = OO_PAGE_NO;
                [self requestList:courseReq isAdd:NO onLoading:NO];
            };
            view;
        });
    }
    return _termArea;
}

-(GKZYHomeCourseAreaView *)courseArea{
    if (!_courseArea) {
        _courseArea = ({
            GKZYHomeCourseAreaView *view = [GKZYHomeCourseAreaView new];
            view.superController = self;
            view;
        });
    }
    return _courseArea;
}

#pragma mark - UIViewControllerTransitioningDelegate

-(id)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source{
    return self.pushAnimation;
}

-(id)animationControllerForDismissedController:(UIViewController *)dismissed{
    return self.dismissedAnimation;
}

#pragma mark - Tools Methods

-(void)alterError:(NSNotification *)notification{
    [self alterErrorWithMsg:[notification object]];
}

-(void)alterErrorWithMsg:(NSString *)msg{
    JGProgressHUD *HUD = [JGProgressHUD progressHUDWithStyle:JGProgressHUDStyleDark];
    HUD.textLabel.text = msg;
    HUD.indicatorView = [[JGProgressHUDErrorIndicatorView alloc] init];
    [HUD showInView:self.view];
    [HUD dismissAfterDelay:2.0];
}

-(void)alterMsg:(NSString *)resultMsg{
    if (resultMsg && [resultMsg isEqualToString:@"LOGIN_NAME IS NULL"]) {
        [self alert:@"账号为空" withComplete:nil];
    }else if (resultMsg && [resultMsg isEqualToString:@"Password IS NULL"]){
        [self alert:@"密码为空" withComplete:nil];
    }else if (resultMsg && [resultMsg isEqualToString:@"SYSTEM_ERROR"]){
        [self alert:@"用户名或密码错误" withComplete:nil];
    }
}

-(void)alert:(NSString *)massage withComplete:(void(^)())block {
    UILabel *alertLabel = [[UILabel alloc] init];
    alertLabel.frame = CGRectMake(self.view.frame.size.width/3,self.view.frame.size.height-80 , self.view.frame.size.width/3,20);
    alertLabel.backgroundColor = [UIColor darkGrayColor];
    alertLabel.textAlignment = NSTextAlignmentCenter;
    alertLabel.text = massage;
    alertLabel.layer.cornerRadius = 2.0;
    alertLabel.layer.masksToBounds = YES;
    alertLabel.textColor = [UIColor whiteColor];
    alertLabel.font = [UIFont systemFontOfSize:12.0];
    [alertLabel sizeToFit];
    [self.view addSubview:alertLabel];
    [UIView animateWithDuration:1.2 animations:^{
        alertLabel.alpha = 0.0;
    } completion:^(BOOL finished) {
        [alertLabel removeFromSuperview];
        if (block) { block(); }
    }];
}

-(void)toggleTermArea{
    self.termArea.isShowTerm = !self.termArea.isShowTerm;
}

typedef NS_ENUM(NSUInteger, LinePosition) {
    LinePositionTop,
    LinePositionLeft,
    LinePositionRight,
    LinePositionBottom,
};
-(void)addGapLineWith:(UIView *)view on:(LinePosition)posit{
    //用于防止重复插入
    NSInteger tagNumber = 960;
    switch (posit) {
        case LinePositionTop:
            tagNumber = 961;
            break;
        case LinePositionLeft:
            tagNumber = 962;
            break;
        case LinePositionRight:
            tagNumber = 963;
            break;
        case LinePositionBottom:
            tagNumber = 964;
            break;
        default:
            break;
    }
    UIView *exist = [view viewWithTag:tagNumber];
    if (exist) { return; }
    
    CGFloat lineSizeUnit = 0.5;
    UILabel *line = [UILabel new];
    line.backgroundColor = [UIColor lightGrayColor];
    line.tag = tagNumber;
    
    [view addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        if (posit==LinePositionRight || posit==LinePositionLeft) {
            if (posit==LinePositionRight) {
                make.right.equalTo(view);
            }else if (posit==LinePositionLeft){
                make.left.equalTo(view);
            }
            make.top.equalTo(view);
            make.height.equalTo(view);
            make.width.equalTo(@(lineSizeUnit));
        }else if (posit==LinePositionTop || posit==LinePositionBottom){
            if (posit==LinePositionTop) {
                make.top.equalTo(view);
            }else if (posit==LinePositionBottom){
                make.bottom.equalTo(view);
            }
            make.height.equalTo(@(lineSizeUnit));
            make.width.equalTo(view);
        }
    }];
}
@end
